#include "TcpServer.h"

int flag2 = 1;

char databuf[1024] = {0};

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  // 静态初始化

void* startTcpStmServer(void *arg)
{
    (void)arg;
    int sockfd = createSocket_st(STM_IP, (unsigned short)STM_PORT);

    mainLoop_st(sockfd);

    close(sockfd);
    sockfd = -1;

    return NULL;
}


int createSocket_st(const char* ip, unsigned short port)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd)
    {
        ERROR("socket");
        exit(-1);
    }

    int on = 1;
    if (-1 == (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))))
        ERROR("setsockopt");

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    if (0 == inet_aton(ip, &server_addr.sin_addr))
    {
        ERROR("inet_aton");
        close(sockfd);
        sockfd = -1;
        exit(-1);
    }
    if (-1 == bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)))
    {
        ERROR("bind");
        close(sockfd);
        sockfd = -1;
        exit(-1);
    }

    if (-1 == listen(sockfd, 20))
    {
        ERROR("listen");
        exit(-1);
    }

    printf("STM_Server started on %s:%d\n", ip, port);
    return sockfd;

}

void mainLoop_st(int sockfd)
{
    struct sockaddr_in client_addr;
    unsigned int size = sizeof(client_addr);


    while(1)
    {
        int stm_fd = accept(sockfd, (struct sockaddr*)&client_addr, &size);
        if (-1 == stm_fd)
        {
            ERROR("accept");
            exit(-1);
        }
        
        //char* p = inet_ntoa(client_addr.sin_addr);
        //unsigned short port = ntohs(client_addr.sin_port);
        
        printf("STM_Client has been connected! \n");


        handleData_st(stm_fd);
    }

}

void handleData_st(int actfd)
{
    int ret;
    memset(databuf,0,sizeof(databuf));
    while(1)
    {
        pthread_mutex_lock(&mutex); 
        ret = recv(actfd,databuf,sizeof(databuf)-1,0);
        printf("stm:%s\n",databuf);
        pthread_mutex_unlock(&mutex); 
        if(0 == ret)
        {
            flag2 = 0;
            printf("STM_Client disconnected!\n");
            return ;
        }
        if(-1 == ret)
        {
            ERROR("recv");
            exit(0);
        } 
        if(ret > 0)
        {
            databuf[ret] = '\0';
        }

        usleep(100000);  
    }

}